import React from 'react';
import { Tree, Spin } from 'antd';
import { connect } from 'umi';

class DeptTree extends React.Component<any, any> {
    constructor(props: any) {
        super(props);
        this.state = {
            loading: false,
            dataSource: [],
        }
    }
    onSelect = (selectedKeys: any, info: any) => {
        this.props.setCurrent(info.node);
    };
    onDbSelect = (selectedKeys: any, info: any) => {
    };
    componentDidMount() {
        this.props.onRef(this)
        this.fetchData();
    }
    fetchData = () => {
        this.props.dispatch({
            type: 'Abp/getTreeList',
            payload: {},
            control: 'Department',
        }).then(() => {
            var dataSource = this.mapData(this.props.response.result);
            this.setState({ dataSource });
        });
    }
    onCheck = (checkedKeys: any, info: any) => {
        this.props.setParent(info.node);
    };
    mapData = (parentNode: any) => {
        var treeData: any = []
        if (parentNode) {
            parentNode.map((item: any) => {
                var node = {
                    title: item.deptName,
                    key: item.id,
                    item: item,
                    children: item.children ? this.mapData(item.children) : null
                }
                treeData.push(node)
            });
        }
        return treeData;
    }
    render() {
        const { dataSource } = this.state;
        return (
            <div>
                {
                    dataSource && dataSource.length ? (
                        <Tree
                            checkable
                            defaultExpandAll
                            onSelect={this.onSelect}
                            onDoubleClick={this.onDbSelect}
                            onCheck={this.onCheck}
                            treeData={dataSource}
                        />
                    ) : (
                        <Spin />
                    )
                }
            </div>
        )
    }
}
export default connect(({ Abp, Department }: API.IConnectState) => ({
    response: Abp.response,
    currentUser: Abp.currentUser,
    departments: Department.departments,
}))(DeptTree);